package com.ldcc.report_system.util.http;

import android.accounts.NetworkErrorException;
import android.content.Context;


import androidx.appcompat.app.AlertDialog;

import com.ldcc.report_system.util.AlertUtil;
import com.ldcc.report_system.util.LoadingUtil;

import java.net.ConnectException;
import java.net.UnknownHostException;
import java.util.concurrent.TimeoutException;

import rx.Observer;

/**
 * @param <T>
 * @author wwj[yeshengkele@outlook.com]
 * @description 请求成功失败、网络异常时的回调,它实现的Observer类,其中成功失败主要在Onext方法里处理
 */
public abstract class HttpObserver<T> implements Observer<ServerResponse<T>> {

    private Context mContext;
    private AlertDialog alertDialog = null;

    public HttpObserver(Context mContext) {
        this.mContext = mContext;
    }

    /**
     * @param mContext    上下文
     * @param alertDialog 加载框，然后在后面的方法，默认关闭加载框
     * @description 带加载框的构造方法
     */
    public HttpObserver(Context mContext, AlertDialog alertDialog) {
        this.mContext = mContext;
        this.alertDialog = alertDialog;
    }

    @Override
    public void onCompleted() {
        if (this.alertDialog != null) {
            LoadingUtil.dialogLoadingClose(alertDialog);
        }
    }

    /**
     * 排除异常
     */
    @Override
    public void onError(Throwable e) {
        if (e instanceof ConnectException ||
                e instanceof TimeoutException ||
                e instanceof NetworkErrorException ||
                e instanceof UnknownHostException) {
            try {
                onFailure(e, false);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        } else {
            try {
                onFailure(e, true);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }


    @Override
    public void onNext(ServerResponse<T> response_entity) {
        if (response_entity.isSuccess()) {
            onSuccess(response_entity);
        } else {
            onCodeError(response_entity);
        }
    }

    /**
     * 请求成功且返回码为0的回调方法,这里抽象方法申明
     *
     * @param response_entity 2
     */
    public abstract void onSuccess(ServerResponse<T> response_entity);

    /**
     * 请求成功但返回的code码不是0的回调方法,这里有默认实现
     *
     * @param response_entity 0
     */
    public void onCodeError(ServerResponse<T> response_entity) {
        AlertUtil.shortTime(response_entity.getMsg());
        if (this.alertDialog != null) {
            LoadingUtil.dialogLoadingClose(alertDialog);
        }
    }

    /**
     * 请求失败回调方法,这里有默认实现
     */
    public void onFailure(Throwable e, boolean netWork) throws Exception {
        e.printStackTrace();
        AlertUtil.shortTime("请求失败");
        if (this.alertDialog != null) {
            LoadingUtil.dialogLoadingClose(alertDialog);
        }
    }
}
